﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace PServiceBus.WebAPI.Transports {
    internal class ForeverFrameTransport : BaseHttpTransport {
        protected string frameScript,
            initialHtml = 
            @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN"" ""http://www.w3.org/TR/html4/strict.dtd"">
            <html><head>
            <meta http-equiv=""content-type"" content=""text/html;charset=UTF-8"" />
            <script>window.onError=null;</script>
            </head><body>",
            frameID = string.Empty;

        internal override string ContentType {
            get { return "text/html"; }
        }

        internal override void Init() {
            frameID = QueryString["frameid"];
            var script = String.Format(@"
                <script type='text/javascript'>
                    function p(msg){{
                        try{{
                            parent.postMessage(msg, '*');
                        }}
                        catch(ex){{ console.log(ex.description || ex.message); }}
                    }}
                </script>");
            frameScript = "<script>p('" + frameID + "|||{0}');</script>";
            Writer.WriteLine(initialHtml);
            Writer.WriteLine(script);
        }

        protected override void Write(string json) {
            Writer.WriteLine(String.Format(frameScript, json));
        }
    }
}
